//
//  NetworkTools.swift
//  AFNetworkingToolsSwift
//
//  Created by 杨运旺 on 15/11/9.
//  Copyright © 2015年 杨运旺. All rights reserved.
//

import UIKit
import AFNetworking

 /// HTTP 请求方法枚举
enum YYRequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

// MARK: - 网络工具
class NetworkTools:  AFHTTPSessionManager{
    
    // MARK: - 应用程序信息
    private let appKey="3617399672"
    private let appSecret="bcad202eaee1727282916562ea2cebf8"
    private let redirectUrl="http://www.baidu.com"
    
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias YYRequestCallBack = (result: AnyObject?, error: NSError?)->()
 
    // 单例
    static let sharedTools:NetworkTools = {
        let tools = NetworkTools(baseURL: nil);
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    /// 返回token字典
//    private var tokenDict:[String: AnyObject]?{
//        
//        if var token = UserAccountViewModel.sharedUserAccount.accessToken{
//        return ["access_token" : token]
//        }
//        return nil
//    }
}

// MARK: - 微博数据相关方法
extension NetworkTools{
    /// 加载微博数据
    ///
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(finished:YYRequestCallBack){
        // 1. 获取ToKen字典
        guard let params = UserAccountViewModel.sharedUserAccount.tokenDict else {
            finished(result: nil, error: NSError(domain: "cn.itheima.error", code: -1001, userInfo: ["message": "字典为空"]))
            return
        }
         // 2.准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 3.发起网络请求
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
    
}

// MARK: - 用户相关方法
extension NetworkTools{
    /// 加载用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter accessToken: accessToken
    /// - parameter finished:    完成回调
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    
    
    func loadUserInfo(uid:String,finished:YYRequestCallBack){
        // 1. 获取ToKen字典
        guard var params = UserAccountViewModel.sharedUserAccount.tokenDict else {
            finished(result: nil, error: NSError(domain: "cn.itheima.error", code: -1001, userInfo: ["message": "字典为空"]))
            return
        }
        
        // 2. 网络访问
        let urlString = "https://api.weibo.com/2/users/show.json"
        params["uid"] = uid
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
    
    
}



// MARK: - OAuth 相关方法
extension NetworkTools{
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL:NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    /// 加载AccessToKen
    func loadAccessToKen(code: String,finished: YYRequestCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
        "client_id":appKey,
        "client_secret":appSecret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
        // 测试返回的数据内容 - AFN 默认的响应格式是 JSON，会直接反序列化
        // 如果要确认数据格式的问题
        // 如果是 NSNumber，则没有引号！在做 KVC 指定属性类型非常重要！
        //        // 1> 设置相应数据格式是二进制的
        //        responseSerializer = AFHTTPResponseSerializer()
        //
        //        // 2> 发起网络请求
        //        POST(urlString, parameters: params, success: { (_, result) -> Void in
        //
        //            // 将二进制数据转换成字符串
        //            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
        //
        //            print(json)
        //
        //            // {"access_token":"2.00ml8IrF6dP8NEb33e7215aeRhrcdB",
        //            // "remind_in":"157679999",
        //            // "expires_in":157679999,
        //            // "uid":"5365823342"}
        //            
        //            }, failure: nil)
    }
}

 


// MARK: - 封装 AFN 网络方法

extension NetworkTools {
   private func request(method: YYRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: YYRequestCallBack) {
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
        finished(result: result, error: nil)
        }
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
        // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
        print(error)
        finished(result: nil, error: error)
        }
        
        if method == YYRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}
